package yja.gzw.app.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import yja.gzw.app.R
import yja.gzw.app.adapter.FabuAdapter
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityPingjiaBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.File

class PingjiaActivity :BaseActivity<Mainviewmodel, ActivityPingjiaBinding>(R.layout.activity_pingjia),  FabuAdapter.OnItemClickListener{
    var fengyi=0f
    var fenger=0f
    private lateinit var fabiada: FabuAdapter
    public var list= mutableListOf<ZaoShuju>(
        ZaoShuju(2,""),

        )
    var file: File?=null
    override fun initView() {
        val ids =intent.getStringExtra("idss")
        viewmodel.onwodezhuyewang(UserData.token,mapOf("id" to ""))


        binding.review.layoutManager=
            GridLayoutManager(this, 3)
        fabiada= FabuAdapter(this,list,this)
        binding.review.adapter= fabiada

        binding.ratingBar.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
            binding.fengshu.text="${rating}分"
            fengyi=rating

        }


        binding.ratingBar2.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
            fenger=rating
            if(rating==0f||rating==0.5f){
                binding.pingtu.setImageResource(R.mipmap.pingjia1)
                binding.pingzi.text="差评"
            }else if(rating==1f||rating==1.5f){
                binding.pingtu.setImageResource(R.mipmap.pingjia2)
                binding.pingzi.text="中评"
            }else if(rating==2f||rating==2.5f){

                binding.pingtu.setImageResource(R.mipmap.pingjia3)
                binding.pingzi.text="一般"
            }else if(rating==3f){
                binding.pingtu.setImageResource(R.mipmap.pingjia3)
                binding.pingzi.text="一般"

            }else if(rating==4f||rating==3.5f){
                binding.pingtu.setImageResource(R.mipmap.pingjia4)
                binding.pingzi.text="满意"
            }else{
                binding.pingtu.setImageResource(R.mipmap.pingjia5)
                binding.pingzi.text="好评"
            }



        }

        binding.tijiao.setOnClickListener {
            var imagess=""
            for ( (index , zaoShuju)in list.withIndex()) {
                if(index==list.size-1){
                    imagess=imagess+zaoShuju.tupian
                }else{

                    imagess=imagess+zaoShuju.tupian+","
                }

            }

            viewmodel.onpingjiawang(UserData.token,mapOf("order_id" to ids!!,"content" to binding.shurukuangss.text.toString(),"score" to fengyi.toString(),"img" to imagess,"score_level" to fenger.toString()))



        }


    }

    override fun dataObservese() {
        viewmodel.onpingjia.observe(this, Observer {

            if(it.code==1){
                val intent=Intent(this,FabidingdanActivity::class.java)
                startActivity(intent)
                finish()

            }else{
                Toast.makeText(this,it.msg, Toast.LENGTH_SHORT).show()
            }

        })


        viewmodel.onlusc.observe(this, Observer {
            if(it.code==1){
                list.add(0,ZaoShuju(1,it.data.url))
                Log.e("上传图片的半路径",it.data.url)
                binding.review.layoutManager=
                    GridLayoutManager(this, 3)
                fabiada= FabuAdapter(this,list,this)
                binding.review.adapter= fabiada

                Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show()

            }


        })



        viewmodel.onwodezhuye.observe(this, Observer {
            if(it.code==1){
                binding.name.text=it.data.nickname
                if(it.data.avatar==""){
                    binding.touxiang.setImageResource(R.mipmap.touxiang)
                }else{
                    val requestOptions = RequestOptions.bitmapTransform(CircleCrop())
                    Glide.with(this).load("http://117ai.32.hzgqapp.com/"+it.data.avatar)
                        .apply(requestOptions)
                        .into(binding.touxiang)
                }
            }


        })

    }

    override fun onItemClick(position: Int, uri: ZaoShuju) {
        if(uri.leixing==2){
            openGallery()

        }else{
            Toast.makeText(this, "图片预览中"+"    "+list.size, Toast.LENGTH_SHORT).show()


        }

    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, GALLERY_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GALLERY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            data?.data?.let { uri ->
                file = File(getRealPathFromURI(uri))

                val requestFile = file?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                val body = MultipartBody.Part.createFormData("file", file?.name,requestFile!!)
                viewmodel.onluying(body)
            }
        }
    }

    private fun getRealPathFromURI(contentUri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = contentResolver.query(contentUri, projection, null, null, null)
        val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val result = cursor?.getString(column_index!!)
        cursor?.close()
        return result!!
    }
    companion object {
        private const val GALLERY_REQUEST_CODE = 1001
    }
}